import React, { useEffect, useState } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import { NavBar, Avatar, Button, Toast } from "antd-mobile";
import { UserOutline, PhonebookOutline, SendOutline, MoreOutline } from "antd-mobile-icons";
import axios from "../axios";
import styles from "./PersonalDetails.module.css";

interface Comment {
    text: string;
    timestamp: string;
    user_id: {
        _id: string;
        userName: string;
        img: string;
    };
}

interface Activity {
    _id: string;
    content: string;
    title?: string;
    img?: string;
    media_type?: 'image' | 'video';
    location?: string;
    time?: string;
    createdAt?: string;
    like: string[];
    comment: Comment[];
}

interface UserData {
    _id: string;
    userName: string;
    phoneNumber: string;
    gender: string;
    age: number;
    balance: number;
    img: string;
    posts: Activity[];
}

const PersonalDetails: React.FC = () => {
    const [searchParams] = useSearchParams();
    const navigate = useNavigate();
    const [userData, setUserData] = useState<UserData | null>(null);
    const [loading, setLoading] = useState(true);
    const [isFollowing, setIsFollowing] = useState(false);
    const userId = searchParams.get('userId');
    const currentUserId = localStorage.getItem('user_id');

    useEffect(() => {
        const fetchUserData = async () => {
            if (!userId) {
                Toast.show({
                    icon: 'fail',
                    content: '用户ID不存在'
                });
                return;
            }

            try {
                setLoading(true);
                // 获取用户基本信息
                const userResponse = await axios.get(`/llx/user/${userId}`);
                // 获取用户的帖子
                const postsResponse = await axios.get(`/llx/user/posts/${userId}`);
                // 检查是否已关注
                if (currentUserId) {
                    const followResponse = await axios.get(`/llx/following/${currentUserId}`);
                    setIsFollowing(followResponse.data.following?.includes(userId) || false);
                }

                if (userResponse.data.code === 200 && postsResponse.data.code === 200) {
                    setUserData({
                        ...userResponse.data.data,
                        posts: postsResponse.data.data || []
                    });
                }
            } catch (error) {
                console.error('获取用户数据失败:', error);
                Toast.show({
                    icon: 'fail',
                    content: '获取用户数据失败'
                });
            } finally {
                setLoading(false);
            }
        };

        fetchUserData();
    }, [userId, currentUserId]);

    const handleFollow = async () => {
        if (!currentUserId) {
            Toast.show({
                icon: 'fail',
                content: '请先登录'
            });
            return;
        }

        if (userId === currentUserId) {
            Toast.show({
                icon: 'fail',
                content: '不能关注自己'
            });
            return;
        }

        try {
            const response = await axios.post('/llx/follow', {
                followerId: currentUserId,
                followingId: userId
            });

            if (response.data.code === 200) {
                setIsFollowing(!isFollowing);
                Toast.show({
                    icon: 'success',
                    content: response.data.message
                });
            }
        } catch (error) {
            console.error('关注操作失败:', error);
            Toast.show({
                icon: 'fail',
                content: '操作失败，请稍后重试'
            });
        }
    };

    if (loading) {
        return <div className={styles.loading}>加载中...</div>;
    }

    if (!userData) {
        return <div className={styles.error}>用户不存在</div>;
    }

    return (
        <div className={styles.container}>
            <NavBar onBack={() => navigate(-1)}>个人详情</NavBar>
            
            <div className={styles.userCard}>
                <div className={styles.userHeader}>
                    <Avatar src={userData.img} className={styles.avatar} />
                    <div className={styles.userInfo}>
                        <h2 className={styles.username}>{userData.userName}</h2>
                        {userId !== currentUserId && (
                            <Button
                                color={isFollowing ? 'default' : 'primary'}
                                onClick={handleFollow}
                                className={styles.followButton}
                            >
                                {isFollowing ? '已关注' : '关注'}
                            </Button>
                        )}
                    </div>
                </div>

                <div className={styles.userDetails}>
                    <div className={styles.detailItem}>
                        <UserOutline className={styles.icon} />
                        <span>年龄: {userData.age}岁</span>
                    </div>
                    <div className={styles.detailItem}>
                        <SendOutline className={styles.icon} />
                        <span>性别: {userData.gender}</span>
                    </div>
                    <div className={styles.detailItem}>
                        <PhonebookOutline className={styles.icon} />
                        <span>电话: {userData.phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}</span>
                    </div>
                    <div className={styles.detailItem}>
                        <MoreOutline className={styles.icon} />
                        <span>余额: {userData.balance} 洋币</span>
                    </div>
                </div>
            </div>

            <div className={styles.postsSection}>
                <h3 className={styles.sectionTitle}>动态</h3>
                <div className={styles.postsList}>
                    {userData.posts.map((post) => (
                        <div key={post._id} className={styles.postCard}>
                            <div className={styles.postHeader}>
                                <span className={styles.postTime}>{post.time}</span>
                                {post.location && (
                                    <span className={styles.postLocation}>
                                        📍 {post.location}
                                    </span>
                                )}
                            </div>
                            
                            <div className={styles.postContent}>
                                <p>{post.content || post.title}</p>
                                {post.img && post.media_type === 'image' && (
                                    <img src={post.img} alt="动态图片" className={styles.postImage} />
                                )}
                                {post.img && post.media_type === 'video' && (
                                    <video
                                        src={post.img}
                                        controls
                                        className={styles.postVideo}
                                    />
                                )}
                            </div>

                            <div className={styles.postStats}>
                                <span>❤️ {post.like.length}</span>
                                <span>💬 {post.comment.length}</span>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
};

export default PersonalDetails;